package com.hky.mopicturebackend.manager;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.hky.mopicturebackend.common.ResultUtils;
import com.hky.mopicturebackend.config.CosClientConfig;
import com.hky.mopicturebackend.exception.BusinessException;
import com.hky.mopicturebackend.exception.ErrorCode;
import com.hky.mopicturebackend.exception.ThrowUtils;
import com.hky.mopicturebackend.model.dto.file.UpdatePictureResult;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


/**
 * 上传文件方法(已废弃)
 *
 * @author hky
 */
@Slf4j
@Service
@Deprecated
public class FileManager {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;

    /**
     * 上传图片方法
     *
     * @param multipartFile 图片文件，通过此参数接收前端上传的图片
     * @param uploadPathPrefix 图片上传路径前缀，用于指定图片在服务器上的保存路径
     * @return 返回一个UpdatePictureResult对象，包含图片上传后的相关信息
     * @throws BusinessException 当图片上传失败时抛出的业务异常
     */
    public UpdatePictureResult uploadPicture(MultipartFile multipartFile, String uploadPathPrefix){
        // 校验图片
        validPicture(multipartFile);
        // 图片上传地址
        String uuid = RandomUtil.randomString(16);
        String originalFilename = multipartFile.getOriginalFilename();
        String uploadFilename = String.format("%s_%s.%s", DateUtil.formatDate(new Date()),uuid,
                FileUtil.getSuffix(originalFilename));
        String uploadPath = String.format("%s/%s", uploadPathPrefix, uploadFilename);
        File file = null;
        try {
            // 上传文件
            file = File.createTempFile(uploadPath, null);
            multipartFile.transferTo(file);
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            int picWidth = imageInfo.getWidth();
            int picHeight = imageInfo.getHeight();
            double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();

            // 构建并返回图片上传结果
            UpdatePictureResult updatePictureResult = new UpdatePictureResult();
            updatePictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
            updatePictureResult.setPicName(FileUtil.mainName(originalFilename));
            updatePictureResult.setPicSize(FileUtil.size(file));
            updatePictureResult.setPicWidth(picWidth);
            updatePictureResult.setPicHeight(picHeight);
            updatePictureResult.setPicScale(picScale);
            updatePictureResult.setPicFormat(imageInfo.getFormat());

            // 返回可访问地址
            return updatePictureResult;
        } catch (Exception e) {
            log.error("图片上传失败 ", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            // 临时文件清理
            this.deleteTempFile(file);
        }
    }

    private static void deleteTempFile(File file) {
        if (file != null) {
            // 删除临时文件
            boolean delete = file.delete();
            if (!delete) {
                log.error("删除文件失败");
            }
        }
    }

    /**
     * 校验文件
     * @param multipartFile
     */
    private void validPicture(MultipartFile multipartFile) {
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "上传文件为空");
        // 校验文件大小
        long fileSize = multipartFile.getSize();
        final long ONE_M = 1024 * 1024;
        ThrowUtils.throwIf(fileSize > 2 * ONE_M, ErrorCode.PARAMS_ERROR, "文件大小不能超过 2M");
        // 校验文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        final List<String> ALLOW_FORMAT_LIST = Arrays.asList("jpeg", "jpg", "png", "webp");
        ThrowUtils.throwIf(!ALLOW_FORMAT_LIST.contains(fileSuffix), ErrorCode.PARAMS_ERROR, "不支持文件格式");
    }

}
